//
//  YWUpdateViewController.m
//  百布业务
//
//  Created by 陈炳桦 on 15/11/10.
//  Copyright © 2015年 陈炳桦. All rights reserved.
//  修改需求

#import "YWUpdateViewController.h"
#import <UIImageView+WebCache.h>
#import "BRPlaceholderTextView.h"
#import <MBProgressHUD.h>
#import "YWImageService.h"
#import "YWSelectSampleController.h"

@interface YWUpdateViewController ()

@property (nonatomic,strong) NSArray *conentArray;

// 提示符
@property (nonatomic,strong) MBProgressHUD *HUD;

/** 显示的图片数组 */
@property (nonatomic,strong) NSArray *currentImages;

/** 原来的图片数组 */
@property (nonatomic,strong) NSArray *originalImages;

/** 新增的图片数组 */
@property (nonatomic,strong) NSArray *addImages;

@end

@implementation YWUpdateViewController

- (instancetype)init
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

#pragma mark - 懒加载
- (NSArray *)conentArray{
    if (_conentArray == nil) {
        _conentArray = @[@"类别",@"品种",@"数量",@"描述",@"手机",@"其他说明"];
    }
    return _conentArray;
}

- (MBProgressHUD *)HUD{
    if (_HUD == nil) {
        _HUD = [[MBProgressHUD alloc] initWithView:self.view];
        _HUD.mode = MBProgressHUDModeText;
        _HUD.margin = 20.f;
        [self.view addSubview:_HUD];
    }
    return _HUD;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"修改需求";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(summit)];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditind) name:@"YWInputView" object:nil];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(select:) name:@"YWSelectSampleController" object:nil];
}

- (void)endEditind{
    [self.view endEditing:YES];
}

- (void)select:(NSNotification *)notifacation{

    ((UILabel *)[self.view viewWithTag:1]).text = notifacation.object;
}

// 提交
- (void)summit{
//    NSString *leibie = ((UITextField *)[self.view viewWithTag:1]).text; //类别
    NSString *pinzhong = ((UITextField *)[self.view viewWithTag:2]).text; //品种
    NSString *shuliang = ((UITextField *)[self.view viewWithTag:3]).text; //数量
    NSString *miaoshu = ((UITextField *)[self.view viewWithTag:4]).text; //描述
    NSString *shouji = ((UITextField *)[self.view viewWithTag:5]).text; //手机
    NSString *qitashuoming = ((BRPlaceholderTextView *)[self.view viewWithTag:6]).text; //其他说明
    
    if ([pinzhong isEmpty] || [shuliang isEmpty] ||[miaoshu isEmpty] || [shouji isEmpty]){
        
        self.HUD.labelText = @"请补全相应的信息";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
        return;
    }
    
    // 上传图片操作
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"memo"] = qitashuoming; // 其他说明
    param[@"desc"] = miaoshu;   // 描述
    param[@"mobile"] = shouji;  // 手机
    param[@"needCount"] = shuliang; // 数量
    param[@"keyWord"] = pinzhong;   // 品种
    param[@"sampleTypeId"] = [self getSampleTypeID];    // 类别
    param[@"buyerDemandId"] = self.mydemand.ID;  // ID
    param[@"keedFiles"] = [self getKeedFiles];   // 原来的网络文件URL地址
    
    param[@"workerId"] = [YWUserInfo sharedUseInfo].workId;
    param[@"adminId"] = [YWUserInfo sharedUseInfo].workId;
    param[@"accessToken"] = [YWUserInfo sharedUseInfo].accessToken;
    
    NSLog(@"%@",param);
    
    self.HUD.labelText = @"上传中...";
    [self.HUD show:YES];
    
     NSString *url = [NSString stringWithFormat:@"%@demand/update",[YWNetwork getDomain]];
    [manager POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
//        NSData *imageData = [YWImageService compressTheBBImage:[UIImage imageNamed:@"take_photo_icon"]];
//        
//        [formData appendPartWithFileData:imageData name:@"files" fileName:@"filename.png" mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        self.HUD.labelText = [NSString stringWithFormat:@"%@请下拉刷新查看",responseObject[@"msg"]];
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:3];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 跳回我的发布页面
            [self.navigationController popToViewController:self.navigationController.childViewControllers[1] animated:YES];
        });
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        self.HUD.labelText = @"出现未知错误！";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];


    }];
    

}

- (NSNumber *)getSampleTypeID{
    NSString *leibie = ((UITextField *)[self.view viewWithTag:1]).text; //类别
    if ([leibie isEqual:@"面料"]) {
        return @1;
    }else{
        return @2;
    }

}

- (NSString *)getKeedFiles{
    
    return @"";
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 200;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 5) {
        return 300;
    }
    return 44;
}

// headerview
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BBScreenW, 100)];
    
    CGFloat imageW = 80;
    CGFloat imageH = 80;
    CGFloat space = 10;     // 间距
    NSInteger count = 4;     // 一排4个
    
    for (int i = 0; i < self.mydemand.urls.count; i++) {
        CGFloat imageX = (i % count)  * (imageW + space) + space;
        CGFloat imageY = (i / count)  * (imageH + space) + space;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
        
        NSURL *url = [NSURL URLWithString:self.mydemand.urls[i]];
        [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"default_no_img"]];
        [headerView addSubview:imageView];
    }
    
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.conentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    // 取消选中状态
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.textLabel.text = self.conentArray[indexPath.row];
    cell.accessoryView = [self getAccessoryView:indexPath.row + 1];
    
    return cell;
}

- (UIView *)getAccessoryView:(NSInteger)index{
    
    
    // 0.AccessoryView是UILable类的
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 31)];
    label1.textAlignment = NSTextAlignmentRight;
    label1.tag = index;
    if (index == 1) {
        if ([self.mydemand.sampleTypeId isEqualToString:@"2"])
            label1.text = @"辅料";
        else
            label1.text = @"面料";
        return label1;
    }

    // 1.AccessoryView是UITextField类的
    UITextField *label = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 31)];
    label.inputAccessoryView = [[NSBundle mainBundle] loadNibNamed:@"YWInputView" owner:nil options:nil][0];
    label.clearButtonMode = UITextFieldViewModeWhileEditing;
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor grayColor];
    label.textAlignment = NSTextAlignmentRight;
    label.tag = index;
    
    switch (index) {
            
        case 2: // 品种
            label.placeholder = @"请填写品种";
            label.text = self.mydemand.keyWord;
            return label;
            break;
            
        case 3: // 数量
            label.placeholder = @"请填写采购数量";
            label.text = self.mydemand.needCount;
            return label;
            break;
            
        case 4: // 描述
            label.placeholder = @"请填写需求描述";
            label.text = self.mydemand.sampleDescribe;
            return label;
            break;
            
        case 5: // 手机
            label.placeholder = @"请填写采购手机";
            label.text = self.mydemand.mobile;
            return label;
            break;
            
        default:
            break;
    }

    // 2.AccessoryView是BRPlaceholderTextView类(带placeholder的UITextView)的
    BRPlaceholderTextView *textView = [[BRPlaceholderTextView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
    textView.inputAccessoryView = [[NSBundle mainBundle] loadNibNamed:@"YWInputView" owner:nil options:nil][0];
    textView.font = [UIFont systemFontOfSize:16];
    textView.textAlignment = NSTextAlignmentRight;
    textView.tag = index;
    if (index == 6) {
        textView.placeholder = @"请填写其他说明，内容仅后台可见";
        textView.text = self.mydemand.demandMemo;
        return textView;
    }

    
    return nil;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) { // 点击类别
        YWSelectSampleController *selectVC = [[YWSelectSampleController alloc] init];
        [self.navigationController pushViewController:selectVC animated:YES];
    }
}


@end














